from django.shortcuts import render

# Create your views here.
from QQLoginTool.QQtool import OAuthQQ
from rest_framework.response import Response

from rest_framework.views import APIView

from mall import settings
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQUserSerializer
from oauth.utils import generic_openid_token
from utils.create_token import create_token


class OauthQQUrlAPIView(APIView):
    # /oauth/qq/statues/
    def get(self,request):

        # auth_url = 'https://graphgeneric_.qq.com/oauth2.0/authorize?response_type=code&client_id=101474184&redirect_uri=http://www.meiduo.site:8080/oauth_callback.html&state=test'
        state = '/'

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        auth_url = qq.get_qq_url()

        return Response({'auth_url':auth_url})

from cart.utils import merge_cookie_to_redis
class OAuthQQUserAPIView(APIView):

    def get(self,request):
        # 1. 接收code
        code = request.query_params.get('code')
        if code is None:
            from rest_framework import status

            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 2. 通过code换取token （是我们通过 请求 向腾讯的服务器换）

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI)
        token = qq.get_access_token(code)

        # 3. 通过token换取openid (openid是此网站上唯一对应用户身份的标识)
        openid = qq.get_open_id(token)
        print(openid)
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            openid_token = generic_openid_token(openid)
            print(openid_token)
            return Response({'access_token':openid_token})
        else:
            from rest_framework_jwt.settings import api_settings
            jwt__payload_handler =api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt__payload_handler(qquser.user)
            token = jwt_encode_handler(payload)

            return Response({
                'user_id':qquser.user.id,
                'username':qquser.user.username,
                'token':token,
            })

    def post(self, request):
        """openid绑定到用户"""

        # 获取序列化器对象
        serializer = OAuthQQUserSerializer(data=request.data)
        # 开启校验
        serializer.is_valid(raise_exception=True)
        # 保存校验结果，并接收
        qquser = serializer.save()

        # 生成JWT token，并响应
        token = create_token(qquser.user)

        response = Response({
            'token': token,
            'user_id': qquser.user.id,
            'username': qquser.user.username
        })
        response = merge_cookie_to_redis(request, qquser, response)
        return response


#weibo
from oauth.weibo_sdk import OAuthWeibo
class WeiboAothURLViiew(APIView):
    def get(self,request):
        # 1.获取state
        state = request.query_params.get('state')
        if not next:
            state = "/"
        # 2.使用sdk进行获取url
        oauth = OAuthWeibo(client_id=settings.WEIBO_CLIENT_ID,
                           client_secret=settings.WEIBO_CLIENT_SECRET,
                           redirect_uri=settings.WEIBO_REDIRECT_URI,
                           state=state)
        login_url = oauth.get_weibo_url()
        # 3.返回url
        return Response({"login_url": login_url})


from cart.utils import merge_cookie_to_redis
from oauth.models import OAuthSinaUser
from oauth.serializers import WeiboOauthSerializers
class WeiboOauthView(APIView):
    def get(self,request):
        # 1.获取code值
        code = request.query_params.get("code")
        # 2.检查参数
        if not code:
            return Response({'errors': '缺少code值'}, status=400)
        # 3.获取token值
        state = '/'
        oauth = OAuthWeibo(client_id=settings.WEIBO_CLIENT_ID,
                           client_secret=settings.WEIBO_CLIENT_SECRET,
                           redirect_uri=settings.WEIBO_REDIRECT_URI,
                           state=state)
        weibotoken = oauth.get_access_token(code=code)
        # 4.判断是否绑定过美多
        try:
            weibo_user = OAuthSinaUser.objects.get(access_token=weibotoken)
        #     4.1未绑定进入绑定页面
        except:
            from oauth.utils import generic_access_token
            access_token = generic_access_token(weibotoken)

            return Response({'access_token': access_token})
        #     4.2绑定查询登录
        #         4.2.1生成token值登录
        else:
            from rest_framework_jwt.settings import api_settings
            jwt__payload_handler =api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt__payload_handler(weibo_user.user)
            token = jwt_encode_handler(payload)

            response = Response(
                {
                    'token': token,
                    'user_id': weibo_user.user.id,
                    'username': weibo_user.user.username
                })
            return response


    def post(self, request):
        """openid绑定到用户"""

        # 获取序列化器对象
        serializer = WeiboOauthSerializers(data=request.data)
        # 开启校验
        serializer.is_valid(raise_exception=True)
        # 保存校验结果，并接收
        weibo_user = serializer.save()

        # 生成JWT token，并响应
        token = create_token(weibo_user.user)

        response = Response({
            'token': token,
            'user_id': weibo_user.user.id,
            'username': weibo_user.user.username
        })

        response = merge_cookie_to_redis(request, weibo_user, response)

        return response
